//
//  NetworkLink.m
//  Login
//
//  Created by mac on 17/2/21.
//  Copyright © 2017年 ZF. All rights reserved.
//

#import "NetworkLink.h"

static NetworkLink *network;
@implementation NetworkLink
#pragma mark - 判断是否登录
+ (void)ifHasLogin
{
    AppDelegate *delegate = [Helps app];
    UIStoryboard *story = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    LoginVC *vc = [story instantiateViewControllerWithIdentifier:@"login"];
    vc.navigationItem.hidesBackButton = YES;

    if(delegate.ifLogin == NO)
    {
    
           UIViewController *con = [Helps getCurrentViewController];
           [con.navigationController pushViewController:vc animated:YES];
  
    }
    else if(delegate.ifLogin == YES)
    {
        [self loginWithName:delegate.userName Password:delegate.password complete:^(BOOL ok) {
            if(ok == NO)
            {
                NSLog(@"登录失败");
                delegate.ifLogin = NO;
                [delegate.userdefault setBool:NO forKey:@"IfLogin"];
                [delegate.userdefault setObject:@"" forKey:@"UserName"];
                [delegate.userdefault setObject:@"" forKey:@"Password"];
                [delegate.userdefault synchronize];
                
                UIViewController *con = [Helps getCurrentViewController];
                [con.navigationController pushViewController:vc animated:YES];
          
            }
        }];
    }
}

#pragma mark - 登录接口
+ (void)loginWithName:(NSString *)name Password:(NSString *)password complete:(void (^)(BOOL))handle
{
    NSString *string = @"login";
    NSDictionary *param  = @{
        @"name":name,
        @"password":password
    };
  
    [self netWorkLinkWithParam:param method:@"GET" bodyData:nil URL:string dataClass:[LoginDataResponse class] complete:^(LoginDataResponse *res) {
        if(res.errcode == 0)
        {
            dispatch_sync(dispatch_get_main_queue(), ^{
                handle(YES);
                NSLog(@"登录成功");
              
                [Helps showTips:@"登录成功" forTime:1 inView:[Helps window] yOffset:1];
            });
        }
        else if(res.errcode == 2)
        {
            dispatch_sync(dispatch_get_main_queue(), ^{
                handle(NO);
                NSLog(@"用户账号或密码错误");
                 [Helps showTips:@"用户账号或密码错误" forTime:1 inView:[Helps window] yOffset:1];
            });
        }
        else if(res.errcode == 3)
        {
            dispatch_sync(dispatch_get_main_queue(), ^{
                handle(NO);
                 [Helps showTips:@"错误" forTime:1 inView:[Helps window] yOffset:1];
            });
        }
    }];
}

#pragma mark - 注销接口
+ (void)logOffUserComplete:(void (^)(BOOL))handle
{
    NSString *string = @"logout";
    [self netWorkLinkWithParam:nil method:@"GET" bodyData:nil URL:string dataClass:[DataResponse class] complete:^(DataResponse *res) {
        if(res.errcode == 0)
        {
            dispatch_sync(dispatch_get_main_queue(), ^{
                handle(YES);
                NSLog(@"注销成功");
                 [Helps showTips:@"注销成功" forTime:1 inView:[Helps window] yOffset:1];
            });
        }
        else if(res.errcode == 1)
        {
            dispatch_sync(dispatch_get_main_queue(), ^{
                handle(NO);
                NSLog(@"注销失败");
                 //[Helps showTips:@"注销失败" forTime:1 inView:[Helps window] yOffset:1];
            });
        }
    }];
}

#pragma mark - 用户列表接口
+ (void)userLoginListComplete:(void (^)(UserList *list))handle
{
    NSString *string = @"users/list";
    [self netWorkLinkWithParam:nil method:@"GET" bodyData:nil URL:string dataClass:[UserList class] complete:^(UserList *res) {
        handle(res);
    }];
}

#pragma mark - 部门列表接口
+ (void)userDepartmentListComplete:(void (^)(DepartmentList *d))handle
{
    NSString *string = @"department/list";
    [self netWorkLinkWithParam:nil method:@"GET" bodyData:nil URL:string dataClass:[DepartmentList class] complete:^(DepartmentList *res) {
        if(res.errcode == 0)
        {
            for(DepartmentListItem *item in res.record)
            {
                NSLog(@"%@",item.name);
            }
        }
        handle(res);
    }];
}

#pragma mark - 获取当前版本
+ (void)getCurrentVersionComplete:(void (^)(NSString *version))handle
{
    NSString *string = @"version";
    [self netWorkLinkWithParam:nil method:@"GET" bodyData:nil URL:string dataClass:[VersionNumber class] complete:^(VersionNumber *res) {
        if(res.errcode == 0)
        {
            handle(res.record.version);
        }
    }];
}

#pragma mark - 修改用户
+ (void)setUserName:(NSString *)name Password:(NSString *)password Department:(NSString *)department Id:(NSString *)Id complete:(void (^)(BOOL))handle
{
    NSString *string = @"users/update";
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObject:name forKey:@"name"];
    [param setObject:password forKey:@"password"];
    if(department)
    {
        [param setObject:department forKey:@"department"];
    }
    [param setObject:Id forKey:@"id"];
    [self netWorkLinkWithParam:param method:@"GET" bodyData:nil URL:string dataClass:[DataResponse class] complete:^(DataResponse *res) {
        if(res.errcode == 0)
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                handle(YES);
                NSLog(@"修改成功");
            });
        }
        else
        {
            dispatch_async(dispatch_get_main_queue(), ^{
            handle(NO);
            NSLog(@"修改失败");
            });
        }
    }];
}

#pragma mark - 初始化
- (instancetype)init
{
    self = [super init];
    if(self)
    {
        NSString *url = @"http://a.xl18z.cn/api/";
        self.baseURL = url;
    }
    return self;
}

#pragma mark - 单例
+ (instancetype)sharedNetworkInstance
{
    //dispatch_once不仅意味着代码仅会被运行一次，而且还是线程安全的
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        network = [[self alloc] init];
    });
    return network;
}


#pragma mark - 基层
+ (void)netWorkLinkWithParam:(NSDictionary *)param method:(NSString *)method bodyData:(NSString *)body URL:(NSString *)url dataClass:(Class)DataClass complete:(void (^)(id res))handle
{
    if(!network)
    {
        [self sharedNetworkInstance];
    }
    url = [network.baseURL stringByAppendingString:url];
    
    NSString *urlString;
    if(param){
        NSMutableArray *arr = [NSMutableArray new];
            for(NSString *key in param.allKeys)
            {
                [arr addObject:[NSString stringWithFormat:@"%@=%@",key,param[key]]];
            }
        urlString = [arr componentsJoinedByString:@"&"];
        url = [url stringByAppendingString:[NSString stringWithFormat:@"?%@",urlString]];
    }
    
    NSLog(@"访问地址：%@",url);
    
    NSURL *path = [NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:path cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
    
    NSURLSession *sessions = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [sessions dataTaskWithRequest:req completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if(error)
        {
            NSLog(@"网络异常");
            NSString *tip = @"网络异常,请检查网络配置";
            if(error.code == NSURLErrorTimedOut)
            {
                NSLog(@"请求超时");
                tip = @"请求超时";
            }
            DataResponse *res = [DataResponse new];
            res.errcode = 4000;
            res.errmsg = tip;
            dispatch_sync(dispatch_get_main_queue(), ^{
                [Helps showTips:tip forTime:1 inView:[Helps window] yOffset:1];
            });
            handle(res);
            return ;
        }
        
        NSString *resText = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"结果：%@",resText);
        
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSInteger ercode = [[dict objectForKey:@"errcode"] integerValue];
        
        if(ercode == 1)
        {
            DataResponse *res = [DataResponse new];
            res.errcode = ercode;
            res.errmsg = @"未登录";
            dispatch_sync(dispatch_get_main_queue(), ^{
                [Helps showTips:@"未登录,登录已过期" forTime:1 inView:[Helps window] yOffset:1];
                [self ifHasLogin];
            });
            
            handle(res);
            return ;
        }
        else if(dict){
            id res = [[DataClass alloc] initWithDictionary:dict];
            handle(res);
            
        }else {
            DataResponse *res = [DataResponse new];
            res.errmsg = @"访问网络出了问题，请稍后重试";
            res.errcode = 4001;
            dispatch_async(dispatch_get_main_queue(), ^{
                [Helps showTips:res.errmsg forTime:2 yOffset:200];
            });
            handle(res);
            return ;
        }
    }];
    [task resume];
}

@end
